/* $Id: ContestProblemScoreModel.java 137 2011-08-29 20:33:36Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.models.scores;

import java.util.List;
import java.util.HashMap;
import java.util.Map;

import org.hibernate.criterion.Order;

import alt.djudge.frontend.server.Deployment;
import alt.djudge.frontend.server.datatypes.ContestProblemEntry;
import alt.djudge.frontend.server.datatypes.scores.ContestProblemScoreEntry;
import alt.djudge.frontend.server.models.AbstractBigtableModelCore;
import alt.djudge.frontend.server.models.AbstractDBModelCore;
import alt.djudge.frontend.server.models.ContestProblemsModel;
import alt.djudge.frontend.server.models.CoreInterface;


public class ContestProblemScoreModel
{
	private static CoreInterface<ContestProblemScoreEntry> core = Deployment.isGAE() ?  
		new AbstractBigtableModelCore<ContestProblemScoreEntry>()
		{
			@Override
			protected Order getOrdering()
			{
				return Order.asc("id");
			}
			
			@Override
			protected Class<ContestProblemScoreEntry> getEntryClass()
			{
				return ContestProblemScoreEntry.class;
			}
		}
	:
		new AbstractDBModelCore<ContestProblemScoreEntry>()
		{
			@Override
			protected Order getOrdering()
			{
				return Order.asc("id");
			}
			
			@Override
			protected Class<ContestProblemScoreEntry> getEntryClass()
			{
				return ContestProblemScoreEntry.class;
			}
		};
	
	
	public static ContestProblemScoreEntry getContestProblemEntry(Long contestId, Long contestProblemId)
	{
		ContestProblemScoreEntry entry = null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("contestId", contestId);
		map.put("contestProblemId", contestProblemId);
		List<ContestProblemScoreEntry> list = (List<ContestProblemScoreEntry>) core.getEntries(map);
		if (list.size() > 0)
		{
			entry = list.get(0);
		}
		else
		{
			entry = new ContestProblemScoreEntry(contestId, contestProblemId);
			entry.makePersistent();
		}
		return entry;
	}

	public static void deleteAllEntries()
	{
		core.deleteAllEntries();
	}
	
	public static List<ContestProblemScoreEntry> getAllEntries()
	{
		List<ContestProblemScoreEntry> list = (List<ContestProblemScoreEntry>) core.getAllEntries();
		return list;
	}
	
	// FIXME:
	// clear on
	// 
	// 
	public static Map<Long, ContestProblemScoreEntry> getContestProblemEntries(Long contestId)
	{
		Map<Long, ContestProblemScoreEntry> map = new HashMap<Long, ContestProblemScoreEntry>();
		List<ContestProblemEntry> problemEntries = ContestProblemsModel.getContestEntries(contestId);
		for (ContestProblemEntry problemEntry : problemEntries)
		{
			ContestProblemScoreEntry entry = getContestProblemEntry(contestId, problemEntry.getId());
			map.put(problemEntry.getId(), entry);
		}
		return map;
	}
}




